import moment from 'moment'
import { serialize } from './transformation.js'
import common from '@/utils/common.js'

/**
 * 本文件主要负责旧系统病历的转换及过程，大部分都是旧系统复制过来的
 * 如果有core问题请看旧系统emr业务，再决定是否改动
 */

export function convertEmrWithOldEmr(oldObj, birthday) {
  const { id, patientId, composition, medication } = oldObj
  // 转obj
  const oldEmrContent = common.initJSONWithTranslator(composition)
  const medicationContent = common.initJSONWithTranslator(medication)
  const tmp = { ...oldEmrContent, ...medicationContent }

  const isReview = oldEmrContent['reviewChiefComplaint'] ? true : false
  const oldEmrObj = isReview
    ? genReviewEmrTextContent(tmp, birthday)
    : genFirstEmrTextContent(tmp, birthday)
  const convertEmr = convertEmrInfo(oldEmrObj)
  convertEmr['xiaomanNewEmrType'] = 'oldEmr'
  if (
    medicationContent.diagnosticRequest &&
    medicationContent.diagnosticRequest.remark
  ) {
    const { patientId, patientDocumentId, createDate } =
      medicationContent.diagnosticRequest.remark
    convertEmr['patientId'] = patientId
    convertEmr['patientDocumentId'] = patientDocumentId
    const timeStr = createDate ? createDate : '暂无数据'
    return {
      type: 'oldEmr',
      isReview,
      emrData: convertEmr,
      doctors: `${isReview ? '复诊' : '首诊'} 病历时间: ${timeStr}`,
    }
  }
  return {
    type: 'oldEmr',
    isReview,
    emrData: convertEmr,
    doctors: `${isReview ? '复诊' : '首诊'} 病历时间: 暂无数据`,
  }
}

/**
 * 传入旧文件的病历和药品对象
 * @param {*} oldEmr
 */
export function convertEmrInfo(oldEmr) {
  const oldTransform = {
    复诊: 'review',
    主诉: 'mainSuit',
    现病史: 'historyPresent',
    既往史: 'past',
    过敏史: 'allergy',
    个人史: 'personal',
    家族史: 'family',
    辅助检查: 'auxiliaryExamination',
    体格检查: 'signs',
    治疗方案: 'treatmentOpinion',
  }
  const tmp = {}
  oldEmr.map((item) => {
    const key = oldTransform[item.name]
    tmp[key] = {
      text: item.text.join('.'),
      imgUrls: removeAuthToken(item.imgUrls),
    }
  })
  return tmp
}
function removeAuthToken(imgUrls = []) {
  console.log('imgUrls =' + JSON.stringify(imgUrls))
  return imgUrls.map(({ url, thumbNail }) => {
    let afterUrl = ''
    if (url) {
      const urls = url.split('?')
      if (urls.length >= 1) {
        afterUrl = urls[0]
      }
    }
    if (!afterUrl) {
      const urls = thumbNail.split('?')
      if (urls.length >= 1) {
        afterUrl = urls[0]
      }
    }
    return { url: afterUrl }
  })
}
// function converMedicine() {

// }
/**
 * 转化首诊
 * @param fragmentVModel
 * @param birthDate
 */
export function genFirstEmrTextContent(fragmentVModel, birthDate) {
  let age = moment().diff(moment(birthDate), 'year')
  let presentIllnessHistoryStr =
    serialize.repeatReason(fragmentVModel) +
    serialize.multiReason(fragmentVModel) +
    serialize.fluquency(fragmentVModel) +
    serialize.season(fragmentVModel) +
    serialize.reveribility(fragmentVModel) +
    serialize.otherPersonality(fragmentVModel)

  let temp = [
    {
      name: '主诉',
      text: [serialize.chiefComplaint(fragmentVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '现病史',
      text: [presentIllnessHistoryStr],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '既往史',
      text: [serialize.pastHistory(fragmentVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '个人史',
      text: [serialize.personalHistory(fragmentVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '家族史',
      text: [serialize.familyHistory(fragmentVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '体格检查',
      text: [serialize.bodyCheck(fragmentVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '辅助检查',
      text: [serialize.assExam(fragmentVModel)],
      imgUrls: pureCopy(fragmentVModel.assExam.lungThumbnail || []).concat(
        pureCopy(fragmentVModel.assExam.allergenImgurl || [])
      ),
      isNameAdded: false,
    },
    {
      name: '诊断',
      text: [serialize.diagnostic(fragmentVModel, age)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '治疗方案',
      text: [serialize.diagnosticRequest(fragmentVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '附件',
      text: [''],
      imgUrls: pureCopy(fragmentVModel.attachments || []),
      isNameAdded: false,
    },
  ]

  return temp
}

export function genReviewEmrTextContent(fragmentReviewVModel, birthDate) {
  let age = moment().diff(moment(birthDate), 'year')
  let temp = [
    {
      name: '复诊',
      text: [serialize.reviewChiefComplaint(fragmentReviewVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '体格检查',
      text: [serialize.bodyCheck(fragmentReviewVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '辅助检查',
      text: [serialize.assExam(fragmentReviewVModel)],
      imgUrls: pureCopy(
        fragmentReviewVModel.assExam.lungThumbnail || []
      ).concat(pureCopy(fragmentReviewVModel.assExam.allergenImgurl || [])),
      isNameAdded: false,
    },
    {
      name: '诊断',
      text: [serialize.diagnostic(fragmentReviewVModel, age)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '治疗方案',
      text: [serialize.diagnosticRequest(fragmentReviewVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '检查结果',
      text: [serialize.checkResult(fragmentReviewVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '附件',
      text: [''],
      imgUrls: pureCopy(fragmentReviewVModel.attachments),
      isNameAdded: false,
    },
  ]

  temp = temp.filter((item) => item.text[0] || item.imgUrls.length)
  return temp
}
// 剔除 vue observer的拷贝
// 注意不能拷贝function, 自引用对象等等
function pureCopy(source) {
  return JSON.parse(JSON.stringify(source))
}
